﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Heritage.Codebox;

namespace Heritage.Controllers
{
    public class FileController : Controller
    {
        [AuthorizedValidated]
        public ActionResult Upload()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file.ContentLength > 0 && file.ContentLength <= 5*1024*1024)
            {
                string name = Guid.NewGuid().ToString("N");
                string filePath = Path.Combine(HttpContext.Server.MapPath("/uploads")
                , name);
                ResizeFromStream(file.InputStream);
            }

            return new RedirectResult("/");
        }

        public void ResizeFromStream(Stream Buffer)
        {

            Image imgInput = Image.FromStream(Buffer);

            //Determine image format
            ImageFormat fmtImageFormat = ImageFormat.Png;

            //get image original width and height
            int intOldWidth = imgInput.Width;
            int intOldHeight = imgInput.Height;

            int intNewWidth = intOldWidth;
            int intNewHeight = intOldHeight;
            //determine if landscape or portrait

            if (intOldWidth > 200)
            {
                //set new width and height
                double dblCoef = 200 / (double)intOldWidth;
                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                if (intNewHeight > 400)
                {
                    dblCoef = 400 / (double)intNewHeight;
                    intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                    intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                }
            }
            //create new bitmap
            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

            //save bitmap to disk
            Utils.SaveImage(bmpResized);

            //release used resources
            imgInput.Dispose();
            bmpResized.Dispose();
            Buffer.Close();
        } 
    }
}
